package com.lc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.exception.BusinessException;
import com.lc.mapper.PPARMapper;
import com.lc.mapper.PmsSpuMapper;
import com.lc.pojo.PmsProductAttributeRel;
import com.lc.pojo.PmsSpu;
import com.lc.pojo.dto.PmsSpuDto;
import com.lc.pojo.param.PmsSpuParam;
import com.lc.result.Page;
import com.lc.result.ResultEnum;
import com.lc.service.PmsSpuService;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PmsSpuServiceImpl extends ServiceImpl<PmsSpuMapper, PmsSpu> implements PmsSpuService {

    @Resource
    private PmsSpuMapper pmsSpuMapper;

    @Resource
    private PPARMapper pparMapper;

    @Override
    public Page<PmsSpuDto> getPmsSpuList(PmsSpuParam psp) {
        List<Long> listPPA = null;
        if (CollectionUtils.isNotEmpty(psp.getProductAttributeIds())) {
            LambdaQueryWrapper<PmsProductAttributeRel> wrapperPPA = new LambdaQueryWrapper<>();
            wrapperPPA.select(PmsProductAttributeRel::getId)
                    .in(PmsProductAttributeRel::getId, psp.getProductAttributeIds());
            listPPA = pparMapper.selectList(wrapperPPA).stream()
                    .map(PmsProductAttributeRel::getId)
                    .collect(Collectors.toList());
        }

        LambdaQueryWrapper<PmsSpu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(psp.getBrandId() != null && psp.getBrandId() != 0, PmsSpu::getBrandId, psp.getBrandId())
                .like(StringUtils.isNotEmpty(psp.getKeyword()), PmsSpu::getName, psp.getKeyword())
                .eq(psp.getProductLevel1CategoryId() != null, PmsSpu::getCid1, psp.getProductLevel1CategoryId())
                .eq(psp.getProductLevel2CategoryId() != null, PmsSpu::getCid2, psp.getProductLevel2CategoryId())
                .in(CollectionUtils.isNotEmpty(listPPA), PmsSpu::getId, listPPA)
                .orderBy(psp.getSort() == 2, false, PmsSpu::getSale)
                .orderBy(psp.getSort() == 3, false, PmsSpu::getCommentTotalScore);

        List<PmsSpu> list = pmsSpuMapper.selectList(wrapper);
        List<PmsSpuDto> listDto = list.stream()
                .map(ps -> {
                    PmsSpuDto pmsSpuDto = new PmsSpuDto();
                    BeanUtils.copyProperties(ps, pmsSpuDto);
                    return pmsSpuDto;
                })
                .collect(Collectors.toList());

        Page<PmsSpuDto> page = new Page<>(listDto, psp.getPageNo(), psp.getPageSize(), listDto.size());
        if(page == null ){
            throw new BusinessException(ResultEnum.COMMON_EXCEPTION);
        }
        return page;
    }
}
